using B.S.XZYData.Api.Wrter.Application.Command.Approval;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Approval
{
    /// <summary>
    /// 处理审批操作处理器
    /// </summary>
    public class ProcessApprovalHandler : IRequestHandler<ProcessApprovalCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<WorkflowInstanceModel> _workflowInstanceRepo;
        private readonly IBaseRepository<AuditModel> _auditRepo;
        private readonly ILogger<ProcessApprovalHandler> _logger;

        public ProcessApprovalHandler(
            IBaseRepository<WorkflowInstanceModel> workflowInstanceRepo,
            IBaseRepository<AuditModel> auditRepo,
            ILogger<ProcessApprovalHandler> logger)
        {
            _workflowInstanceRepo = workflowInstanceRepo;
            _auditRepo = auditRepo;
            _logger = logger;
        }

        public async Task<ApiResult<bool>> Handle(ProcessApprovalCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<bool>();
            
            try
            {
                // 开始事务
                await _workflowInstanceRepo.BeginTranAsync();

                try
                {
                    // 1. 查询流程实例
                    var workflowInstance = await _workflowInstanceRepo.GetValue(request.WorkflowInstanceId);
                    if (workflowInstance == null)
                    {
                        res.Code = ApiEnum.Fail;
                        res.Msg = "流程实例不存在";
                        return res;
                    }

                    // 2. 验证当前状态是否允许审批
                    if (workflowInstance.Status == "通过" || workflowInstance.Status == "驳回")
                    {
                        res.Code = ApiEnum.Fail;
                        res.Msg = "该流程已完成，不能重复审批";
                        return res;
                    }

                    // 3. 验证审批权限（可选：检查是否为指定审批人）
                    if (!string.IsNullOrEmpty(workflowInstance.AuditUserId) && 
                        workflowInstance.AuditUserId != request.AuditUserId.ToString())
                    {
                        res.Code = ApiEnum.Fail;
                        res.Msg = "您没有权限审批此流程";
                        return res;
                    }

                    // 4. 更新流程实例状态
                    var newStatus = request.OperationType == "通过" ? "通过" : "驳回";
                    workflowInstance.Status = newStatus;
                    workflowInstance.AuditUserName = request.AuditUserName;
                    workflowInstance.AuditUserId = request.AuditUserId.ToString();
                    workflowInstance.StepName = request.StepName ?? "审批完成";
                    workflowInstance.ModifyTime = DateTime.Now;
                    
                    if (newStatus == "通过" || newStatus == "驳回")
                    {
                        workflowInstance.CompletedTime = DateTime.Now;
                    }

                    await _workflowInstanceRepo.UpdateAsync(workflowInstance);

                    // 5. 记录审批历史
                    var auditRecord = new AuditModel
                    {
                        WorkflowId = request.WorkflowInstanceId.ToString(),
                        StepId = "STEP_" + request.WorkflowInstanceId,
                        StepName = request.StepName ?? "审批",
                        ExecutePointerId = "EP_" + request.WorkflowInstanceId,
                        AuditUserName = request.AuditUserName,
                        AuditUserId = request.AuditUserId,
                        OperationType = request.OperationType,
                        Remark = request.Comment,
                        Status = request.OperationType == "通过",
                        CreateTime = DateTime.Now,
                        CreatorId = (int)request.AuditUserId
                    };

                    await _auditRepo.CreateAsync(auditRecord);

                    // 6. 如果是通过，可以在这里添加后续业务逻辑
                    if (request.OperationType == "通过")
                    {
                        // TODO: 可以在这里添加通过后的业务处理
                        // 比如更新报工状态、发送通知等
                        _logger.LogInformation("审批通过，流程实例ID: {WorkflowInstanceId}", request.WorkflowInstanceId);
                    }
                    else if (request.OperationType == "驳回")
                    {
                        // TODO: 可以在这里添加驳回后的业务处理
                        // 比如发送驳回通知等
                        _logger.LogInformation("审批驳回，流程实例ID: {WorkflowInstanceId}", request.WorkflowInstanceId);
                    }

                    // 提交事务
                    await _workflowInstanceRepo.CommitTranAsync();

                    res.Code = ApiEnum.Success;
                    res.Msg = $"审批{request.OperationType}成功";
                    res.Data = true;

                    return res;
                }
                catch (Exception)
                {
                    // 回滚事务
                    await _workflowInstanceRepo.RollbackTranAsync();
                    throw;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理审批失败，WorkflowInstanceId: {WorkflowInstanceId}, OperationType: {OperationType}", 
                    request.WorkflowInstanceId, request.OperationType);
                res.Code = ApiEnum.Fail;
                res.Msg = "审批处理失败：" + ex.Message;
                res.Data = false;
                return res;
            }
        }
    }
} 